package com.xuecheng.media.service.impl;

import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.model.dto.UploadFileParamsDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.service.BigFilesService;
import com.xuecheng.media.service.MediaFileService;
import com.xuecheng.model.RestResponse;
import io.minio.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: chenheng
 * @Date: 2023/12/22 15:46
 */
@Service
@Slf4j
public class BigFilesServiceImpl implements BigFilesService {
    @Value("${minio.bucket.videofiles}")
    private String video;
    @Autowired
    private MinioClient minioClient;
    @Autowired
    MediaFilesMapper mediaFilesMapper;
    @Autowired
    MediaFileService mediaFileService;

    @Override
    public RestResponse<Boolean> checkFile(String fileMd5) {
        //查询数据库
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);
        if (mediaFiles != null) {
            //查询minio
            String bucket = mediaFiles.getBucket();
            String objectName = mediaFiles.getFilePath();
            GetObjectArgs getFile = GetObjectArgs.builder().bucket(bucket)
                    .object(objectName)
                    .build();
            try {
                InputStream object = minioClient.getObject(getFile);
                if (object != null) {
                    return RestResponse.success(true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //文件不存在
        return RestResponse.success(false);
    }

    @Override
    public RestResponse<Boolean> checkchunk(String fileMd5, int chunk) {
        //得到分块文件的路径
        String chunkPath = getDefaultFolderPath(fileMd5) + chunk;
        GetObjectArgs getFile = GetObjectArgs.builder().bucket(video)
                .object(chunkPath)
                .build();
        try {
            InputStream object = minioClient.getObject(getFile);
            if (object != null) {
                return RestResponse.success(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //分块不存在
        return RestResponse.success(false);
    }

    @Override
    public RestResponse uploadChunk(MultipartFile file, String fileMd5, int chunk) {
        //得到待上传的目录
        String defaultFolderPath = getDefaultFolderPath(fileMd5);
        //获取object
        String object = defaultFolderPath + chunk;
        //获取mineType
        String mineType = mediaFileService.getMineType("");
        try {
            //获取绝对路径
            String localFilePath = getAbsolutePath(file);
            boolean b = mediaFileService.addMediaFilesToMinIO(localFilePath, mineType, video, object);
            if (!b) {
                log.debug("上传分块失败:{}", defaultFolderPath);
                return RestResponse.validfail(false, "上传分块失败");
            }
            log.debug("上传分块文件成功:{}", localFilePath);
            return RestResponse.success(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //上传失败
        return RestResponse.success(false);
    }

    @Override
    public RestResponse mergeChunks(Long companyId, String fileMd5, int chunkTotal, UploadFileParamsDto uploadFileParamsDto) {
        //得到分块的目录
        String ChunkFolderPath = getDefaultFolderPath(fileMd5);
        ArrayList<ComposeSource> composeSources = new ArrayList<>();
        for (int i = 0; i < chunkTotal; i++) {
            ComposeSource build = ComposeSource.builder()
                    .bucket(video)
                    .object(ChunkFolderPath + i)
                    .build();
            composeSources.add(build);
        }
        //----合并----
        //文件名称
        String filename = uploadFileParamsDto.getFilename();
        //文件扩展名
        String extension = filename.substring(filename.lastIndexOf("."));
        //文件mineType
        String mineType = mediaFileService.getMineType("");
        //合并后的目录
        String mergePath = getMergePath(fileMd5,extension);

        try {
            //合并文件
            ComposeObjectArgs videos = ComposeObjectArgs.builder()
                    .bucket(video)
                    .object(mergePath)
                    .sources(composeSources)
                    .build();
            ObjectWriteResponse response = minioClient.composeObject(videos);
            log.debug("合并文件成功:{}",response);
        }catch (Exception e){
            log.debug("合并文件失败,fileMd5:{},异常:{}",fileMd5,e.getMessage(),e);
            return RestResponse.validfail(false, "合并文件失败。");
        }
        // ====验证md5====
        //下载合并后的文件
        File minioFile = downloadFileFromMinIO(video,mergePath);
        if(minioFile == null){
            log.debug("下载合并后文件失败,mergeFilePath:{}",mergePath);
            return RestResponse.validfail(false, "下载合并后文件失败。");
        }
        try (InputStream newFileInputStream = new FileInputStream(minioFile)) {
            //minio上文件的md5值
            String md5Hex = DigestUtils.md5Hex(newFileInputStream);
            //比较md5值，不一致则说明文件不完整
            if(!fileMd5.equals(md5Hex)){
                return RestResponse.validfail(false, "文件合并校验失败，最终上传失败。");
            }
            //文件大小
            uploadFileParamsDto.setFileSize(minioFile.length());
        }catch (Exception e){
            log.debug("校验文件失败,fileMd5:{},异常:{}",fileMd5,e.getMessage(),e);
            return RestResponse.validfail(false, "文件合并校验失败，最终上传失败。");
        }finally {
            if(minioFile!=null){
                minioFile.delete();
            }
        }
        //文件入库 TODO  文件存在应该怎么做，如果是avi视频加入到media_process中
        mediaFileService.addMediaFilesToDb(companyId,fileMd5,uploadFileParamsDto,video,mergePath);
        //=====清除分块文件=====
        clearChunkFiles(ChunkFolderPath,chunkTotal);
        return RestResponse.success(true);
    }

    //得到分块文件的目录
    private String getDefaultFolderPath(String fileMd5) {
        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + "chunk" + "/";
    }

    //合并后的目录
    private String getMergePath(String fileMd5,String extension) {
        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + fileMd5 +extension;
    }

    //得到上传的本地文件的绝对路径
    private String getAbsolutePath(MultipartFile file) throws IOException {
        //创建临时文件
        File tempFile = File.createTempFile("minio", "temp");
        //上传的文件拷贝到临时文件
        file.transferTo(tempFile);
        String absolutePath = tempFile.getAbsolutePath();
        return absolutePath;
    }

    /**
     * 从minio下载文件
     * @param bucket 桶
     * @param objectName 对象名称
     * @return 下载后的文件
     */
    public File downloadFileFromMinIO(String bucket,String objectName){
        //临时文件
        File minioFile = null;
        FileOutputStream outputStream = null;
        try{
            InputStream stream = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .build());
            //创建临时文件
            minioFile=File.createTempFile("minio", ".merge");
            outputStream = new FileOutputStream(minioFile);
            IOUtils.copy(stream,outputStream);
            return minioFile;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 清除分块文件
     * @param chunkFileFolderPath 分块文件路径
     * @param chunkTotal 分块文件总数
     */
    private void clearChunkFiles(String chunkFileFolderPath,int chunkTotal){

        try {
            List<DeleteObject> deleteObjects = Stream.iterate(0, i -> ++i)
                    .limit(chunkTotal)
                    .map(i -> new DeleteObject(chunkFileFolderPath.concat(Integer.toString(i))))
                    .collect(Collectors.toList());

            RemoveObjectsArgs removeObjectsArgs = RemoveObjectsArgs.builder().bucket("video").objects(deleteObjects).build();
            Iterable<Result<DeleteError>> results = minioClient.removeObjects(removeObjectsArgs);
            results.forEach(r->{
                DeleteError deleteError = null;
                try {
                    deleteError = r.get();
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("清楚分块文件失败,objectname:{}",deleteError.objectName(),e);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("清楚分块文件失败,chunkFileFolderPath:{}",chunkFileFolderPath,e);
        }
    }
}
